# -*- coding: utf-8 -*-
# @Time    : 2021/10/19
# @Author  : CHENlj
# @File    : Public.py
import hashlib, time, json, allure
from Common.Request import Request
from Common.ApiAdress import GetToken
from Common import AssertInfo
"""
公共方法、变量
"""

# 设备id
NativeDeviceId = 'ac0ad9f8f8f7927462b4412b91ecf46d53241503dbd0136189e4489970854312'  # 设备id 华为nova8se
DeviceId = hashlib.md5(NativeDeviceId.encode(encoding='UTF-8')).hexdigest()  # MD5加密后的设备id
# 用户token
token = '202824e3ed8b94c7387efd11fd4b51e7'
# 是否审核模式
AuditStatus = 0   # 1 是  0 否
# 赚金币任务ID
DesktopStartup = 62  # 从桌面启动
OpenChest = 17  # 去开宝箱
Watering = 18  # 去浇水
AddDesk = 16  # 添加到桌面
PickSeeds = 6  # 种树赚金币
NativeAdv_task2 = 15  # 看广告赚金币
SignPop = 61  # 签到弹窗

xts = int(time.time())  # 秒级时间戳


def create_sign(path):
    """
    生成Xsign签名验证
    :param path: 接口路径
    :return:
    """
    sign = str(path) + 'yunyousj@2021test' + str(xts)  # 签名
    return hashlib.md5(sign.encode(encoding='UTF-8')).hexdigest()  # MD5加密


def create_default_data(path):
    """
    生成默认请求参数
    :param path:
    :return:
    """
    default_data = {
        "DeviceId": DeviceId,
        "Xts": str(xts),
        "_sign": create_sign(path)
    }
    
    return json.dumps(default_data)


def create_headers(path):
    """
    生成默认请求头
    :param path:
    :return:
    """
    headers = {
                "Brand": "HuaWei",
                "Version": "2.2.2",
                "DeviceId": DeviceId,
                "NativeDeviceId": NativeDeviceId,
                "Accept-Language": "zh-CN",
                "token": token,
                "user-agent": "Mozilla/5.0 (Linux; Android 10; JSC-AN00 Build/HUAWEIJSC-AN00A;)",
                "Content-Type": "application/json",
                "Accept-Encoding": "gzip",
                "Connection": "keep-alive",
                "Xts": str(xts),
                "Xsign": create_sign(path)
            }
    return headers


def api_except(res):
    """
    接口异常信息返回
    :param res:
    :return:
    """
    try:
        res.json()
    except Exception:
        allure.attach(str(res.status_code), 'http请求返回状态码:', allure.attachment_type.TEXT)  # 请求状态码
        allure.attach(res.text, 'http请求结果:', allure.attachment_type.TEXT)  # 请求结果


def attach_info(res, data):
    """
    接口响应正常时测试报告附加信息
    :param res:
    :param data:
    :return:
    """
    allure.attach(data, AssertInfo.AttachReqText, allure.attachment_type.JSON)  # 请求数据
    allure.attach(json.dumps(res.json(), indent=1, ensure_ascii=False), AssertInfo.AttachResText,
                  allure.attachment_type.JSON)  # 返回数据


if __name__ == '__main__':
    print('token:', token)


    def get_token():
        headers = create_headers(GetToken)

        data = {
            "DeviceId": DeviceId
        }
        data = json.dumps(data)

        res = Request.post_request(GetToken, headers=headers, data=data)
        print(res.json())
        global token
        token = res.json()['DATA']
        print('token2:', token)
    get_token()
